import requests
import pandas as pd
from bs4 import BeautifulSoup

# 1. 获取网页数据
url = "https://iftp.chinamoney.com.cn/english/bdInfo/"
params = {
    "bondType": "Treasury Bond",
    "issueYear": 2023
}

response = requests.get(url, params=params)
response.encoding = 'utf-8'

# 2. 解析HTML表格
soup = BeautifulSoup(response.text, 'html.parser')
table = soup.find('table', {'class': 'table table-striped table-bordered'})

# 提取表头
headers = [th.text.strip() for th in table.find('thead').find_all('th')]

# 提取数据行
rows = []
for tr in table.find('tbody').find_all('tr'):
    cells = [td.text.strip() for td in tr.find_all('td')]
    rows.append(cells)

df = pd.DataFrame(rows, columns=headers)


# 4. 保存为CSV
output_file = 'test1.csv'
df.to_csv(output_file, index=False, encoding='utf-8-sig')

print(f"数据已保存至 {output_file}")